from flask import Blueprint,render_template,jsonify
from models import RatingCountTop,Movies
from sqlalchemy import  *
import sqlalchemy.sql.expression as expr

from sqlalchemy.sql.expression import desc
bp = Blueprint("main",__name__)

@bp.route("/")
def index():
    return render_template("index.html")
@bp.route("/get_top")
def get_top():

    # 计算对应的评分
    tops = RatingCountTop.query.join(Movies, RatingCountTop.movieId==Movies.movieId).with_entities(RatingCountTop.movieId,RatingCountTop.ratingCount,RatingCountTop.uptime, Movies.title,
  (RatingCountTop.ratingSum/RatingCountTop.ratingCount).label("ratingAvg")).order_by( desc( RatingCountTop.ratingCount) ).all()

    results = []
    uptime="时间错误"
    for item in tops:
        results.append("{}_{}_{}_{}".format(item.movieId,item.title,item.ratingCount, round( item.ratingAvg,2)))
        uptime = item.uptime
    return jsonify({
        'uptime':uptime,
        'tops':results
    })